import os
import logging

from agent.common.system import sysCommand
from agent.feature.base import Feature

'''
Feature: code_hugepage
Domain: kernel_mem
'''

logger = logging.getLogger('common')

class CodeHugepage(Feature):
    __domain__ = "kernel_mem"
    __feature__ = "code_hugepage"
    
    def __init__(self) -> None:
        """ Check available of this feature, 
        
        Raise exception if file /sys/kernel/mm/transparent_hugepage/hugetext_enabled do not exists

        Raises:
            Exception: feature file do not exists
        """
        super().__init__(self.__domain__, self.__feature__)
        self.hugepage_file = "/sys/kernel/mm/transparent_hugepage/hugetext_enabled"
        if not os.path.exists(self.hugepage_file):
            raise Exception("file {} don't exists.".format(self.hugepage_file))
    
    def set_value(self, value):
        logger.debug("set feature code_hugepage to '{}'".format(value))
        
        if int(value) == 0:
            sysCommand("echo 1 > /sys/kernel/debug/split_huge_pages")
            sysCommand("echo 3 > /proc/sys/vm/drop_caches")
        
        sysCommand("echo {param_value} > {hugepage_file}".format(
            param_value = value,
            hugepage_file = self.hugepage_file
        ))
    
    def get_value(self):
        return sysCommand("cat {hugepage_file}".format(
            hugepage_file = self.hugepage_file
        ))

if __name__ == "__main__":
    handler = CodeHugepage()
    handler.backup()
    handler.set_value(0)
    handler.set_value(1)
    handler.set_value(2)
    handler.set_value(3)
    handler.rollback()